<?php

namespace app\admin\controller;

use think\Request;
use \think\Session;
use \think\Cookie;
use \user\Auth;
use think\Controller;
class Role extends Controller
{

    protected $beforeActionList = [
        'first',
    ];

    protected function first()
    {
        Cookie::init(['prefix'=>'admin_','path'=>'/','httponly'=>true]);
        $token = Cookie::get('token');
        $request = Request::instance();
        $check_res = Auth::check($token,true,Session::get('id'),$request->controller(),$request->action());
        if($check_res['resCode'] == -8){
            Session::delete('id');
            Session::delete('username');
            Session::delete('username_dsp');
            Cookie::delete('token');
            format(-999,$check_res['msg']);
        }else if ($check_res['resCode'] != 2){
            format(-2,$check_res['msg']);
        }
    }

    public function roleList()
    {
        $request = Request::instance();
        $page = $request->post('page');
        $pageSize = $request->post('ps');
        $sort = $request->post('sort', '', 'SAFE_REPLACE,REMOVE_XSS');
        $title = $request->post('title', '', 'SAFE_REPLACE,REMOVE_XSS');

        $page = intval($page);
        $pageSize = intval($pageSize);

        if (empty($page)) {
            $page = 1;
        }

        if (empty($pageSize)) {
            $pageSize = 20;
        }

        switch ($sort) {
            case 'id_desc' :
                $order = array('id' => 'desc');
                break;
            case 'id_asc' :
                $order = array('id' => 'asc');
                break;
            case 'ct_asc' :
                $order = array('create_time' => 'asc');
                break;
            default :
                $order = array('create_time' => 'desc');
                break;
        }

        $params = array(
            'function' => Auth::AUTH_MODULE . ".permission." . "roleList",
            'data' => array(
                'page' => $page,
                'pageSize' => $pageSize,
                'order' => $order,
                'title' => $title
            )
        );
        $param = array(
            'data' => json_encode($params)
        );
        $result = Auth::makeRequest(Auth::AUTH_URL, $param);
        $result = json_decode($result['result'], true);
        if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
            $data = $result['data']['data'];
            $ret = array(
                'roleList' => $data['list'],
                'amount' => $data['amount'],
                'page' => $data['page'],
                'pageSize' => $data['pageSize']
            );
            format(0, 'success', $ret);
        }
        format(-2, 'fail');
    }

    public function addRole()
    {
        $request = Request::instance();
        $title = $request->post('title', '', 'SAFE_REPLACE,REMOVE_XSS');
        if (empty($title)) {
            format(-2, '非法输入');
        }
        $param = array(
            'title' => $title
        );
        $result = Auth::adminServiceRequest('permission.addRole', $param);
        if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
            format(0, '添加成功');
        } else {
            format(-2, '添加失败');
        }
    }

    public function getRole()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $id = intval($id);
        if ($id > 0) {
            $param = array(
                'id' => $id
            );
            $result = Auth::adminServiceRequest('permission.getRoleById', $param);
            if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
                format(0, 'success', $result['data']['data']);
            } else {
                format(-2, 'fail');
            }
        } else {
            format(-2, 'fail');
        }
    }

    public function editRole()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $id = intval($id);
        $title = $request->post('title', '', 'SAFE_REPLACE,REMOVE_XSS');
        if ($id <= 0 || empty($title)) {
            format(-2, '非法输入');
        }
        $param = array(
            'id' => $id,
            'title' => $title
        );
        $result = Auth::adminServiceRequest('permission.editRole', $param);
        if (!empty($result['data']['resCode'] && $result['data']['resCode'] == 2)) {
            format(0, '修改成功');
        } else {
            format(-2, '修改失败');
        }
    }

    public function delRole()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $id = intval($id);
        if ($id > 0) {
            $param = array(
                'id' => $id
            );
            $result = Auth::adminServiceRequest('permission.delRole', $param);
            if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
                format(0, 'success', $result['data']['data']);
            } else {
                format(-2, 'fail');
            }
        } else {
            format(-2, 'fail');
        }
    }

    public function bindRolePage()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $id = intval($id);
        if ($id > 0) {
            $param = array(
                'role_id' => $id
            );
            $result = Auth::adminServiceRequest('permission.getUserRoleList', $param);
            if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
                $userRoleList = $result['data']['data'];
                $right = array();
                $left = array();
                if (!empty($userRoleList)) {
                    foreach ($userRoleList as $userRole) {
                        if (!empty($userRole['role_id']) && intval($userRole['role_id']) > 0) {
                            $roleId = intval($userRole['role_id']);
                            if ($roleId == $id) {
                                $right[] = $userRole['id'];
                            }
                        }
                        $userRoleId = !empty($userRole['role_id'])?intval($userRole['role_id']):'0';
                        $left[] = array(
                            'key' => intval($userRole['id']),
                            'label' => $userRole['username'] . (!empty($userRole['role_name'])?"({$userRole['role_name']})":""),
                            'disabled' =>  $userRoleId === $id
                        );
                    }
                }
                $ret = array('left' => $left, 'right' => $right);
                format(0, 'success', $ret);
            }
            format(-2, '参数错误');
        } else {
            format(-2, 'fail');
        }
    }

    public function bindRole()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $userIds = $request->post('user_ids');
        $id = intval($id);
        $userIds = explode(',', $userIds);
        if ($id <= 0 || empty($userIds)) {
            format(-2, '参数错误');
        }

        foreach ($userIds as $userId) {
            if (intval($userId) <= 0) {
                format(-2, '参数错误');
            }
        }

        foreach ($userIds as $userId) {
            $param = array(
                'role_id' => $id,
                'user_id' => intval($userId)
            );
            Auth::adminServiceRequest('permission.bindRole', $param);
        }
        format(0, 'success');
    }

    public function permissionList()
    {
        $request = Request::instance();
        $page = $request->post('page');
        $pageSize = $request->post('ps');
        $sort = $request->post('sort', '', 'SAFE_REPLACE,REMOVE_XSS');
        $title = $request->post('title', '', 'SAFE_REPLACE,REMOVE_XSS');

        $page = intval($page);
        $pageSize = intval($pageSize);

        if (empty($page)) {
            $page = 1;
        }

        if (empty($pageSize)) {
            $pageSize = 20;
        }

        switch ($sort) {
            case 'id_desc' :
                $order = array('id' => 'desc');
                break;
            case 'id_asc' :
                $order = array('id' => 'asc');
                break;
            case 'ct_asc' :
                $order = array('create_time' => 'asc');
                break;
            default :
                $order = array('create_time' => 'desc');
                break;
        }


        $param = array(
            'page' => $page,
            'pageSize' => $pageSize,
            'order' => $order,
            'title' => $title
        );
        $result = Auth::adminServiceRequest('permission.permissionList', $param);
        if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
            $data = $result['data']['data'];
            $ret = array(
                'permissionList' => $data['list'],
                'amount' => $data['amount'],
                'page' => $data['page'],
                'pageSize' => $data['pageSize']
            );
            format(0, 'success', $ret);
        }
        format(-2, 'fail');
    }

    public function addPermission()
    {
        $request = Request::instance();
        $title = $request->post('title', 'SAFE_REPLACE,REMOVE_XSS');
        $controller = $request->post('controller', '', 'SAFE_REPLACE,REMOVE_XSS');
        $operation = $request->post('operation', '', 'SAFE_REPLACE,REMOVE_XSS');
        if (empty($title) || empty($controller) || empty($operation)) {
            format(-2, '非法输入');
        }
        $param = array(
            'title' => $title,
            'controller' => $controller,
            'operation' => $operation
        );
        $result = Auth::adminServiceRequest('permission.addPermission', $param);
        if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
            format(0, '添加成功');
        } else {
            format(-2, '添加失败');
        }
    }

    public function getPermission()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $id = intval($id);
        if ($id > 0) {
            $param = array(
                'id' => $id
            );
            $result = Auth::adminServiceRequest('permission.getPermissionById', $param);
            if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
                format(0, 'success', $result['data']['data']);
            } else {
                format(-2, 'fail');
            }
        } else {
            format(-2, 'fail');
        }
    }

    public function editPermission()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $id = intval($id);
        $title = $request->post('title', '', 'SAFE_REPLACE,REMOVE_XSS');
        $controller = $request->post('controller', '', 'SAFE_REPLACE,REMOVE_XSS');
        $operation = $request->post('operation', '', 'SAFE_REPLACE,REMOVE_XSS');
        if ($id <= 0 || empty($title)) {
            format(-2, '非法输入');
        }
        $param = array(
            'id' => $id,
            'title' => $title,
            'controller' => $controller,
            'operation' => $operation
        );
        $result = Auth::adminServiceRequest('permission.editPermission', $param);
        if (!empty($result['data']['resCode'] && $result['data']['resCode'] == 2)) {
            format(0, '修改成功');
        } else {
            format(-2, '修改失败');
        }
    }

    public function delPermission()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $id = intval($id);
        if ($id > 0) {
            $param = array(
                'id' => $id
            );
            $result = Auth::adminServiceRequest('permission.delPermission', $param);
            if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
                format(0, 'success', $result['data']['data']);
            } else {
                format(-2, 'fail');
            }
        } else {
            format(-2, 'fail');
        }
    }

    public function bindPermissionForRolePage()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $id = intval($id);
        if ($id > 0) {
            $param = array(
                'role_id' => $id
            );
            $result = Auth::adminServiceRequest('permission.getPermissionListByRole', $param);
            if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
                $permissionRoleList = $result['data']['data'];
                $right = array();
                $left = array();
                if (!empty($permissionRoleList)) {
                    foreach ($permissionRoleList as $permissionRole) {
                        if (!empty($permissionRole['role_id']) && intval($permissionRole['role_id']) > 0) {
                            $roleId = intval($permissionRole['role_id']);
                            if ($roleId == $id) {
                                $right[] = $permissionRole['id'];
                            }
                        }
                        $left[] = array(
                            'key' => intval($permissionRole['id']),
                            'label' => $permissionRole['title']
                        );
                    }
                }
                $ret = array('left' => $left, 'right' => $right);
                format(0, 'success', $ret);
            }
            format(-2, '参数错误');
        } else {
            format(-2, 'fail');
        }
    }

    public function bindPermission()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $type = $request->post('type',1);
        $permissionIds = $request->post('permission_ids');
        $id = intval($id);
        $permissionIds = explode(',', $permissionIds);
        if ($id <= 0 || empty($permissionIds)) {
            format(-2, '参数错误');
        }

        foreach ($permissionIds as $permissionId) {
            if (intval($permissionId) <= 0) {
                format(-2, '参数错误');
            }
        }

        $param = array(
            'role_id' => $id,
            'permission_ids' => $permissionIds,
            'type' => $type
        );

        $result = Auth::adminServiceRequest('permission.bindPermission', $param);

        if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
            format(0, 'success');
        }else{
            format(-2, '操作失败');
        }
    }

    public function bindRoleForPermissionPage()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $id = intval($id);
        if ($id > 0) {
            $param = array(
                'permission_id' => $id
            );
            $result = Auth::adminServiceRequest('permission.getRoleListByPermission', $param);
            if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
                $RoleList = $result['data']['data'];
                $right = array();
                $left = array();
                if (!empty($RoleList)) {
                    foreach ($RoleList as $Role) {
                        if (!empty($Role['permission_id']) && intval($Role['permission_id']) > 0) {
                            $permissionId = intval($Role['permission_id']);
                            if ($permissionId == $id) {
                                $right[] = $Role['id'];
                            }
                        }
                        $left[] = array(
                            'key' => intval($Role['id']),
                            'label' => $Role['title']
                        );
                    }
                }
                $ret = array('left' => $left, 'right' => $right);
                format(0, 'success', $ret);
            }
            format(-2, '参数错误');
        } else {
            format(-2, 'fail');
        }
    }

    public function bindPermissionRole()
    {
        $request = Request::instance();
        $id = $request->post('id');
        $type = $request->post('type',1);
        $roleIds = $request->post('role_ids');
        $id = intval($id);
        $roleIds = explode(',', $roleIds);
        if ($id <= 0 || empty($roleIds)) {
            format(-2, '参数错误');
        }

        foreach ($roleIds as $roleId) {
            if (intval($roleId) <= 0) {
                format(-2, '参数错误');
            }
        }

        $param = array(
            'permission_id' => $id,
            'role_ids' => $roleIds,
            'type' => $type
        );

        $result = Auth::adminServiceRequest('permission.bindPermissionRole', $param);

        if (!empty($result['data']['resCode']) && $result['data']['resCode'] == 2) {
            format(0, 'success');
        }else{
            format(-2, '操作失败');
        }
    }

}